package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.Result;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.mapper.EduVideoMapper;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author 董万均
 * @since 2020-10-25
 */
@Service
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {

    @Autowired
    private VodClient vodClient;

    //删除小结之前，先删除视频
    @Override
    public void removeByCourseId(String courseId) {
        //根据课程id找到视频的id
        QueryWrapper<EduVideo> videoWrapper=new QueryWrapper<>();
        videoWrapper.eq("course_id",courseId);
        videoWrapper.select("video_source_id");//查询的结果只需要视频的id
        List<EduVideo> videoList = baseMapper.selectList(videoWrapper);
        //将List集合转换为字符串
        List<String> videoSourceList=new ArrayList<>();
        //遍历
        for (int i = 0; i < videoList.size(); i++) {
            EduVideo eduVideo = videoList.get(i);
            String videoSourceId= eduVideo.getVideoSourceId();
            if (!StringUtils.isEmpty(videoSourceId)){
                videoSourceList.add(videoSourceId);
            }
        }
        if (videoSourceList.size()>0){
            Result result = vodClient.removeAllVideo(videoSourceList);
            if (result.getCode()==20001){
                throw new GuliException(20001,"删除多个视频，微服务宕机，使用熔断器...");
            }
        }

        QueryWrapper<EduVideo> wrapper=new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);
    }
}
